package com.dpj.wait_test;

import com.sun.webkit.ThemeClient;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

@Slf4j(topic = "c.MessageTest")
public class MessageTest {
    public static void main(String[] args) throws InterruptedException {

        MessageQueue mq=new MessageQueue(2);

        for (int i = 0; i <3 ; i++) {
            int id=i;
            new Thread(()->{
                try {
                    mq.put(new Message(id,"值"+id));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"生产者"+i).start();

        }
        new Thread(()->{
           while(true){
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               try {
                   mq.take();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }

        },"消费者").start();

    }
}

//消息队列类，java线程间通信
@Slf4j(topic = "c.MessageQueue")
class MessageQueue{
    public MessageQueue(int capcity) {
        this.capcity = capcity;
    }

    //消息的队列集合
    private LinkedList<Message> list=new LinkedList<>();
    //队列容量
    private int capcity;
    //获取消息
    public Message take() throws InterruptedException {
        //检查对象是否为空
        synchronized (list) {
            while (list.isEmpty()) {
                log.debug("队列为空,消费者线程等待");
                list.wait();
            }

            //从队列的头部获取消息返回
            Message message = list.removeFirst();
            log.debug("已消费信息{}", message);
            list.notifyAll();
            return message;
        }
    }

    //存入消息
    public void put(Message message) throws InterruptedException {
        synchronized (list){
            //检查对象是否已满
            while(list.size()==capcity){
                log.debug("队列已满,生产者线程等待");
                list.wait();
            }
            //将消息加入队列尾部
            list.addLast(message);

            log.debug("以生产消息{}",message);
            list.notifyAll();

        }
    }
}
@Slf4j(topic = "c.Message")
 final class Message{
    private  int id;
    private  Object value;

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }

    public Message() {
    }

    public int getId() {
        return id;
    }



    public Object getValue() {
        return value;
    }


}